import 'package:blurb/common/routers/names.dart';
import 'package:blurb/common/values/images.dart';
import 'package:blurb/common/values/svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/services/user_service.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/pages/community/sharing_publish.dart';
import 'package:blurb/common/models/comment.dart';
import 'package:blurb/common/services/comment_service.dart';

class SharingPage extends StatefulWidget {
  const SharingPage({super.key});

  @override
  State<SharingPage> createState() => _SharingPageState();
}

class _SharingPageState extends State<SharingPage> {
  int _selectedTabIndex = 0; // 0: All posts, 1: Follow
  bool _isLoading = false;
  
  // 使用PageController来管理内容区域的切换
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _selectedTabIndex);
    _loadShares();
  }
  
  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  Future<void> _loadShares() async {
    final shareStore = Provider.of<ShareStore>(context, listen: false);
    setState(() {
      _isLoading = true;
    });
    
    try {
      await shareStore.refreshShares();
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景图片固定在底部
          Positioned.fill(
            child: Image.asset(MIP.background, fit: BoxFit.cover),
          ),
          // 内容部分
          Column(
            children: [
              // 固定在顶部的标题栏
              SafeArea(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      // 居中的标题
                      Center(
                        child: Text(
                          'Sunscreen Goodies Sharing',
                          style: GoogleFonts.racingSansOne(
                            fontSize: 22.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.white,
                          ),
                        ),
                      ),
                      // 左侧的返回按钮
                      Positioned(
                        left: 0,
                        child: IconButton(
                          onPressed: () {
                            GoRouter.of(context).pop();
                          },
                          icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                        ),
                      ),
                      // 右侧的发布按钮
                      Positioned(
                        right: 0,
                        child: IconButton(
                          onPressed: () {
                            final userStore = Provider.of<UserStore>(context, listen: false);
                            if (userStore.currentUser != null) {
                              GoRouter.of(context).push(RNS.sharingPublish);
                            } else {
                              _showLoginDialog(context);
                            }
                          },
                          icon: Icon(MSI.add, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // 切换类型标签 - 使用固定高度的容器
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _buildTabButton('All posts', 0),
                    SizedBox(width: 40.w),
                    _buildTabButton('Follow', 1),
                  ],
                ),
              ),
              SizedBox(height: 15.h),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? _buildLoadingIndicator()
                    : PageView(
                        controller: _pageController,
                        physics: const NeverScrollableScrollPhysics(), // 禁用滑动，只通过标签切换
                        onPageChanged: (index) {
                          setState(() {
                            _selectedTabIndex = index;
                          });
                        },
                        children: [
                          RefreshIndicator(
                            onRefresh: _loadShares,
                            child: _buildAllPostsList(),
                          ),
                          RefreshIndicator(
                            onRefresh: _loadShares,
                            child: _buildFollowList(),
                          ),
                        ],
                      ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTabButton(String title, int index) {
    final isSelected = _selectedTabIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
          // 使用PageController切换页面，避免布局抖动
          _pageController.animateToPage(
            index,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        });
      },
      child: Container(
        alignment: Alignment.center,
        child: AnimatedDefaultTextStyle(
          duration: Duration(milliseconds: 300),
          style: GoogleFonts.racingSansOne(
            fontSize: isSelected ? 24.sp : 20.sp,
            fontWeight: FontWeight.normal,
            color: isSelected ? Colors.white : Colors.white.withOpacity(0.7),
          ),
          child: Text(title),
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Center(
      child: CircularProgressIndicator(
        color: Color(0xFF60C3FF),
      ),
    );
  }

  Widget _buildAllPostsList() {
    return Observer(
      builder: (_) {
        final shareStore = Provider.of<ShareStore>(context);
        final shares = shareStore.shares;
        
        if (shares.isEmpty) {
          return Center(
            child: Text(
              'No shares yet',
              style: GoogleFonts.inter(
                color: Colors.white70,
                fontSize: 16.sp,
              ),
            ),
          );
        }
        
        // 分享已在 ShareStore 中按时间排序
        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount: shares.length,
          itemBuilder: (context, index) {
            return _buildShareItem(shares[index]);
          },
        );
      },
    );
  }

  Widget _buildFollowList() {
    return ListView(
      children: [
        SizedBox(height: 100.h),
        Center(
          child: Text(
            'Follow feature coming soon',
            style: GoogleFonts.inter(
              color: Colors.white70,
              fontSize: 16.sp,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildShareItem(Share share) {
    // 格式化时间
    final DateTime shareTime = DateTime.parse(share.time);
    final String formattedTime = _formatShareTime(shareTime);
    
    return FutureBuilder<User?>(
      future: UserService.getUserById(share.userId),
      builder: (context, snapshot) {
        final String userName = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.nickname 
            : 'User ${share.userId}';
        final String userAvatar = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.avatar 
            : MIP.avatar;
            
        return GestureDetector(
          onTap: () {
            GoRouter.of(context).push('/community/sharing/detail?id=${share.id}');
          },
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: 15.w,
              vertical: 10.h,
            ),
            margin: EdgeInsets.only(bottom: 16.h),
            decoration: BoxDecoration(
              color: const Color(0xFF1F1F21),
              borderRadius: BorderRadius.circular(19.r),
              border: Border.all(color: Colors.white.withOpacity(0.1)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 48.w,
                      height: 48.h,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: const Color(0xFF60C3FF).withOpacity(0.7),
                          width: 1.5.w,
                        ),
                      ),
                      child: ClipOval(
                        child: Image.asset(userAvatar, fit: BoxFit.cover),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      userName,
                      style: GoogleFonts.racingSansOne(
                        fontSize: 24.sp,
                        fontWeight: FontWeight.normal,
                        color: Colors.white,
                      ),
                      // overflow: TextOverflow.ellipsis,
                      // maxLines: 1,
                    ),
                    SizedBox(width: 10.w),
                    Text(
                      formattedTime,
                      style: GoogleFonts.inter(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.normal,
                        color: Colors.white,
                      ),
                    ),
                    Spacer(),
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 6.h,
                      ),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment(0.50, 0.00),
                          end: Alignment(0.50, 0.96),
                          colors: [
                            const Color(0xFF60C3FF),
                            const Color(0xFFAADEFC),
                          ],
                        ),
                        borderRadius: BorderRadius.circular(37.r),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: 16.w,
                            height: 16.h,
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                              borderRadius: BorderRadius.circular(12.r),
                              border: Border.all(
                                color: Colors.white,
                                width: 1.w,
                              ),
                            ),
                            child: Icon(
                              Icons.favorite_border,
                              color: Colors.white,
                              size: 12.sp,
                            ),
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            'Follow',
                            style: GoogleFonts.inter(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.normal,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10.h),
                Text(
                  share.description,
                  style: GoogleFonts.inter(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.normal,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 10.h),
                // 使用新的方法显示图片
                _buildShareImages(share),
                SizedBox(height: 8.h),
                Row(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 6.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            MSI.collection,
                            color: Colors.white,
                            size: 24.sp,
                          ),
                          SizedBox(width: 6.w),
                          Text(
                            '13',
                            style: GoogleFonts.inter(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.normal,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(width: 4.w),
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 6.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                      ),
                      child: FutureBuilder<List<Comment>>(
                        future: CommentService.getShareComments(share.id),
                        builder: (context, snapshot) {
                          int commentCount = 0;
                          if (snapshot.hasData) {
                            commentCount = snapshot.data!.length;
                          }
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Icon(
                                MSI.comment,
                                color: Colors.white,
                                size: 24.sp,
                              ),
                              SizedBox(width: 6.w),
                              Text(
                                '$commentCount',
                                style: GoogleFonts.inter(
                                  fontSize: 12.sp,
                                  fontWeight: FontWeight.normal,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                    Spacer(),
                    Icon(MSI.report, color: Colors.white, size: 24.sp),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  
  String _formatShareTime(DateTime shareTime) {
    final DateTime now = DateTime.now();
    final Duration difference = now.difference(shareTime);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  // 显示登录提示对话框
  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Please login first',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              GoRouter.of(context).push(RNS.guide);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
            child: Text(
              'Go to login',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 18.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildShareImages(Share share) {
    // 检查是否有发布的图片数据
    final bool hasPublishedImages = SharingPublishPage.publishedImages.containsKey(share.id);
    
    // 确定要显示的图片数量
    final int imageCount = hasPublishedImages 
        ? SharingPublishPage.publishedImages[share.id]!.length 
        : share.pictures.length;
    
    if (imageCount == 0) {
      return const SizedBox.shrink();
    } else if (imageCount == 1) {
      // 单张图片，显示大图
      return ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: hasPublishedImages
            ? Image.memory(
                SharingPublishPage.publishedImages[share.id]![0],
                fit: BoxFit.cover,
                width: double.infinity,
                height: 200.h,
              )
            : Image.asset(
                share.pictures[0],
                fit: BoxFit.cover,
                width: double.infinity,
                height: 200.h,
              ),
      );
    } else {
      // 多张图片，显示网格
      return Row(
        children: List.generate(imageCount, (index) {
          return Expanded(
            child: Padding(
              padding: EdgeInsets.only(right: index < imageCount - 1 ? 8.w : 0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child: hasPublishedImages
                    ? Image.memory(
                        SharingPublishPage.publishedImages[share.id]![index],
                        fit: BoxFit.cover,
                        height: 150.h,
                      )
                    : Image.asset(
                        share.pictures[index],
                        fit: BoxFit.cover,
                        height: 150.h,
                      ),
              ),
            ),
          );
        }),
      );
    }
  }
}
